#!coding=utf-8
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import *
from django.views.decorators.csrf import csrf_exempt
from django.db import transaction

from models import *
from enterprise_chemicals.models import Application_status

from util.form_util import *
from itertools import chain,islice
import simplejson
import datetime

#temp
def chemicalsList(request):
	_enterPrise = request.session.get('ep')
	if request.method == "GET":

		year = request.GET.get('y', None)
		month = request.GET.get('m', None)

		try:
			cs = Chemicals.objects.filter(enterprise = _enterPrise)

			if year and month:
				cs = cs.filter(add_time__year=int(year), add_time__month=int(month))

			paginator = Paginator(cs, 10)
			page = request.GET.get('page')
			cs = paginator.page(page)
		except PageNotAnInteger:
			cs = paginator.page(1)
		except EmptyPage:
			cs = paginator.page(paginator.num_pages)
		except Exception as e:
			return HttpResponse("非法请求\n\n"+ e.message + e)

		return render_to_response('enterprise/chemical_productInfo/chemicals/chemicalList.html', {  'cs':cs, 'paginator':paginator }, context_instance=RequestContext(request))

@csrf_exempt
def chemicalsAdd(request):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		return render_to_response('enterprise/chemical_productInfo/chemicals/chemicalEdit.html', context_instance=RequestContext(request))

	if request.method == 'POST':
		c = Chemicals()
		auto_wear(request, c, 'enterprise_chemicals', 'Chemicals')
		c.enterprise = _enterPrise
		c.save()
		return HttpResponseRedirect('/chemicals/chemicalsList/')

def chemicalsDetail(request,id):
	c = Chemicals.objects.get(id = id)
	return render_to_response('enterprise/chemical_productInfo/chemicals/chemicalDetail.html', { 'c' : c}, context_instance=RequestContext(request))

@csrf_exempt
def chemicalsEdit(request,id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		c = Chemicals.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/chemicals/chemicalEdit.html', { 'c' : c}, context_instance=RequestContext(request))

	if request.method == 'POST':
		c = Chemicals.objects.get(id = id)
		auto_wear(request, c, 'enterprise_chemicals', 'Chemicals')
		c.enterprise = _enterPrise
		c.save()
		return HttpResponseRedirect('/chemicals/chemicalsDetail/%s' % c.id)

def chemicalsDel(request,id):
	c = Chemicals.objects.get(id = id)
	c.delete()
	return HttpResponseRedirect('/chemicals/chemicalsList/')

# 状态修改
@transaction.commit_on_success
def checkAppStatus(request, _type):
	try:
		_enterPrise = request.session.get('ep')
			
		_type = int(_type)

		if _type == 1:
			query = Materials.objects.all()
			app_name = u'原辅料信息'
		elif _type == 2:
			query = InterMeditatesPro.objects.all()
			app_name = u'中间产品信息'
		elif _type == 3:
			query = Product.objects.all()
			app_name = u'产品信息'
		else:
			return HttpResponse(u'禁止访问')

		fill = request.session.get('fill', None)
		
		app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)[0]

		query = query.filter(enterprise = _enterPrise, app_status = app_s)

		query_sub2 = query.filter(submit_type = 2)

		count_q = len(query)

		count_s2 = len(query_sub2)

		if count_q == 0:
			app_s.app_status = '未确认'
		elif count_q > count_s2:
			app_s.app_status = '未确认'
		elif count_q == count_s2:
			app_s.app_status = '已确认'
		
		app_s.save()

	except Exception,e:
		print e.message

#原辅料信息
def materialList(request):
	_enterPrise = request.session.get('ep')
	if request.method == "GET":
		year = request.GET.get('y', None)
		month = request.GET.get('m', None)

		try:
			fill = request.session.get('fill', None)

			app_k = 'S'
			app = Application_status.objects.filter(app_name='原辅料信息', fill_id = fill.id)
				
			if len(app) > 0:
				app = app[0]
			else:
				app = Application_status(app_name='原辅料信息', fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
				app.save()

			ms_app = Materials.objects.filter(submit_type = 2, enterprise = _enterPrise, app_status=app.id)
			ms_none = Materials.objects.filter(submit_type = 1, enterprise = _enterPrise, app_status=app.id)

			ms_query = chain(ms_app, ms_none)
			ms = []

			for obj in ms_query:
				ms.append(obj)

			if year and month:
				ms = ms.filter(add_time__year=int(year), add_time__month=int(month))

			paginator = Paginator(ms, 10)
			page = request.GET.get('page')
			ms = paginator.page(page)

		except PageNotAnInteger:
			ms = paginator.page(1)
		except EmptyPage:
			ms = paginator.page(paginator.num_pages)
		except Exception as e:
			return HttpResponse("非法请求\n\n"+ e.message)

		return render_to_response('enterprise/chemical_productInfo/materials/materialList.html', { 'ms':ms, 'status':fill.status, 'paginator':paginator }, context_instance=RequestContext(request))

@csrf_exempt
@transaction.commit_on_success
def materialAdd(request):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		return render_to_response('enterprise/chemical_productInfo/materials/materialAdd.html', context_instance=RequestContext(request))

	if request.method == 'POST':
		try:
			it = IngredientsType.objects.filter(name='原辅料信息')

			if not it:
				it = IngredientsType(name='原辅料信息')
				it.save()
			else:
				it = it[0]

			m = Materials()
			auto_wear(request, m, 'enterprise_chemicals', 'Materials')
			
			key = request.GET.get('key',None)

			if not key:
				m.submit_type = 2
			else:
				m.submit_type = 1

			fill = request.session.get('fill', None)
			app_k = 'S'
			app_name = u'原辅料信息'
			app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)

			if len(app_s) > 0:
				app_s = app_s[0]
				app_s.app_status = u'未确认'
				app_s.save()
			else:
				app_s = Application_status(app_name=app_name, fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
				app_s.save()

			m.app_status = app_s
			m.enterprise = _enterPrise
			m.save()

			ilist = auto_wear_list(request,Ingredients,"enterprise_chemicals",'Ingredients')

			for i in ilist:
				i.app_status = app_s
				i.save()
				print i
				cr = ChemicalsRelative(cr_type=it, che_entity=m.id, igds_entity=i)
				cr.save()

			checkAppStatus(request, 1)
			return HttpResponseRedirect('/chemicals/materialList/')
		except Exception,e:
			transaction.rollback()
			result = {'error':e.message if '' else (e.__str__()) }
			return HttpResponse(simplejson.dumps(result))

def materialDetail(request,id):
	m = Materials.objects.get(id = id)
	crs = ChemicalsRelative.objects.filter(cr_type__name='原辅料信息', che_entity=id)
	fill = request.session.get('fill', None)

	iis = []
	for cr in crs:
		ii = Ingredients.objects.get(id=cr.igds_entity.id)
		iis.append(ii)

	return render_to_response('enterprise/chemical_productInfo/materials/materialDetail.html', { 'm':m, 'status':fill.status, 'iis':iis }, context_instance=RequestContext(request))

@csrf_exempt
def materialEdit(request,id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		m = Materials.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/materials/materialEdit.html', { 'm': m } ,context_instance=RequestContext(request))

	if request.method == 'POST':
		m = Materials.objects.get(id = id)
		auto_wear(request, m, 'enterprise_chemicals', 'Materials')

		key = request.GET.get('key',None)

		if not key:
			m.submit_type = 2
		else:
			m.submit_type = 1

		m.enterprise = _enterPrise
		m.save()

		checkAppStatus(request, 1)

		return HttpResponseRedirect('/chemicals/materialDetail/%s' % m.id)

@transaction.commit_on_success
def materialDel(request,id):
	try:
		m = Materials.objects.get(id = id)
		crs = ChemicalsRelative.objects.filter(cr_type__name='原辅料', che_entity=m.id)

		for cr in crs:
			ii = Ingredients.objects.get(id=cr.igds_entity.id)
			ii.delete()

			cr.delete()

		m.delete()
		checkAppStatus(request, 1)
		return HttpResponseRedirect('/chemicals/materialList/')

	except Exception,e:
		transaction.rollback()
		result = {'error':e.message if '' else (e.__str__()) }
		return HttpResponse(simplejson.dumps(result))

@csrf_exempt
def materialElEdit(request, id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		i = Ingredients.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/materials/materialElementEdit.html', { 'i':i },context_instance=RequestContext(request))

	if request.method == 'POST':
		i = Ingredients.objects.get(id = id)
		auto_wear(request, i, 'enterprise_chemicals', 'Ingredients')
		i.enterprise = _enterPrise
		i.save()

		cr = i.getBelongstoParent()

		return HttpResponseRedirect('/chemicals/materialDetail/%s' % cr.che_entity)

#产品信息表
def infoList(request):
	_enterPrise = request.session.get('ep')
	if request.method == "GET":

		year = request.GET.get('y', None)
		month = request.GET.get('m', None)

		try:
			fill = request.session.get('fill', None)
			app_k = 'S'
			app = Application_status.objects.filter(app_name='产品信息', fill_id = fill.id)
				
			if len(app) > 0:
				app = app[0]
			else:
				app = Application_status(app_name='产品信息', fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
				app.save()

			ps_app = Product.objects.filter(submit_type = 2, enterprise = _enterPrise, app_status = app )
			ps_none = Product.objects.filter(submit_type = 1, enterprise = _enterPrise, app_status = app )

			ps_query = chain(ps_app, ps_none)
			ps = []

			for obj in ps_query:
				ps.append(obj)

			paginator = Paginator(ps, 10)
			page = request.GET.get('page')
			ps = paginator.page(page)

		except PageNotAnInteger:
			ps = paginator.page(1)
		except EmptyPage:
			ps = paginator.page(paginator.num_pages)
		except Exception as e:
			return HttpResponse("非法请求\n\n"+ e.message)

		return render_to_response('enterprise/chemical_productInfo/product/productInfoList.html', { 'ps':ps, 'status':fill.status, 'paginator':paginator },context_instance=RequestContext(request))

@csrf_exempt
@transaction.commit_on_success
def infoAdd(request):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		return render_to_response('enterprise/chemical_productInfo/product/productInfoAdd.html', context_instance=RequestContext(request))

	if request.method == 'POST':
		try:
			it = IngredientsType.objects.filter(name='产品信息')

			if not it:
				it = IngredientsType(name='产品信息')
				it.save()
			else:
				it = it[0]
				
			p = Product()
			auto_wear(request, p, 'enterprise_chemicals', 'Product')

			key = request.GET.get('key',None)

			if not key:
				p.submit_type = 2
			else:
				p.submit_type = 1

			fill = request.session.get('fill', None)
			app_k = 'S'
			app_name = u'产品信息'
			app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)

			if len(app_s) > 0:
				app_s = app_s[0]
				app_s.app_status = u'未确认'
				app_s.save()
			else:
				app_s = Application_status(app_name=app_name, fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
				app_s.save()

			p.app_status = app_s
			p.enterprise = _enterPrise
			p.save()

			ilist = auto_wear_list(request,Ingredients,"enterprise_chemicals",'Ingredients')

			for i in ilist:
				i.app_status = app_s
				i.save()

				cr = ChemicalsRelative(cr_type=it, che_entity=p.id, igds_entity=i)
				cr.save()

			checkAppStatus(request, 3)
			return HttpResponseRedirect('/chemicals/productList/')
		except Exception,e:
			transaction.rollback()
			result = {'error':e.message if '' else (e.__str__()) }
			return HttpResponse(simplejson.dumps(result))

def infoDetail(request,id):
	p = Product.objects.get(id = id)
	crs = ChemicalsRelative.objects.filter(cr_type__name='产品信息', che_entity=id)

	iis = []
	for cr in crs:
		ii = Ingredients.objects.get(id=cr.igds_entity.id)
		iis.append(ii)

	return render_to_response('enterprise/chemical_productInfo/product/productInfoDetail.html', { 'p':p, 'iis':iis }, context_instance=RequestContext(request))

@csrf_exempt
def infoEdit(request, id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		p = Product.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/product/productInfoEdit.html', { 'p':p },context_instance=RequestContext(request))

	if request.method == 'POST':
		p = Product.objects.get(id = id)
		auto_wear(request, p, 'enterprise_chemicals', 'Product')

		key = request.GET.get('key',None)

		if not key:
			p.submit_type = 2
		else:
			p.submit_type = 1

		p.enterprise = _enterPrise
		p.save()

		checkAppStatus(request, 3)
		return HttpResponseRedirect('/chemicals/productDetail/%s' % p.id)

@transaction.commit_on_success
def infoDel(request, id):
	try:
		p = Product.objects.get(id = id)
		crs = ChemicalsRelative.objects.filter(cr_type__name='产品信息', che_entity=p.id)

		for cr in crs:
			ii = Ingredients.objects.get(id=cr.igds_entity.id)
			ii.delete()

			cr.delete()

		p.delete()

		checkAppStatus(request, 3)
		return HttpResponseRedirect('/chemicals/productList/')
	except Exception,e:
		transaction.rollback()
		result = {'error':e.message if '' else (e.__str__()) }
		return HttpResponse(simplejson.dumps(result))

@csrf_exempt
def elEdit(request, id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		i = Ingredients.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/product/productElementEdit.html', { 'i':i },context_instance=RequestContext(request))

	if request.method == 'POST':
		i = Ingredients.objects.get(id = id)
		auto_wear(request, i, 'enterprise_chemicals', 'Ingredients')
		i.enterprise = _enterPrise
		i.save()

		cr = i.getBelongstoParent()

		return HttpResponseRedirect('/chemicals/productDetail/%s' % cr.che_entity)

#中间产品信息表
def impList(request):
	_enterPrise = request.session.get('ep')
	if request.method == "GET":

		try:
			fill = request.session.get('fill', None)
			app_k = 'S'
			app = Application_status.objects.filter(app_name='中间产品信息', fill_id = fill.id)
				
			if len(app) > 0:
				app = app[0]
			else:
				app = Application_status(app_name='中间产品信息', fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
				app.save()

			imps_app = InterMeditatesPro.objects.filter(submit_type = 2, enterprise = _enterPrise, app_status=app)
			imps_none = InterMeditatesPro.objects.filter(submit_type = 1, enterprise = _enterPrise, app_status=app)

			imps_query = chain(imps_app, imps_none)
			_is = []

			for obj in imps_query:
				_is.append(obj)

			paginator = Paginator(_is, 10)
			page = request.GET.get('page')
			_is = paginator.page(page)

		except PageNotAnInteger:
			_is = paginator.page(1)
		except EmptyPage:
			_is = paginator.page(paginator.num_pages)
		except Exception as e:
			return HttpResponse("非法请求\n\n"+ e.message)

		return render_to_response('enterprise/chemical_productInfo/imp/impList.html', { 'is':_is, 'status':fill.status, 'paginator':paginator },context_instance=RequestContext(request))

@csrf_exempt
@transaction.commit_on_success
def impAdd(request):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		return render_to_response('enterprise/chemical_productInfo/imp/impAdd.html', context_instance=RequestContext(request))

	if request.method == 'POST':
		try:
			it = IngredientsType.objects.filter(name='中间产品信息')

			if not it:
				it = IngredientsType(name='中间产品信息')
				it.save()
			else:
				it = it[0]

			ip = InterMeditatesPro()
			auto_wear(request, ip, 'enterprise_chemicals', 'InterMeditatesPro')

			key = request.GET.get('key',None)

			if not key:
				ip.submit_type = 2
			else:
				ip.submit_type = 1

			fill = request.session.get('fill', None)
			app_k = 'S'
			app_name = u'中间产品信息'
			app_s = Application_status.objects.filter(app_name=app_name, fill_id = fill.id)

			if len(app_s) > 0:
				app_s = app_s[0]
				app_s.app_status = u'未确认'
				app_s.save()
			else:
				app_s = Application_status(app_name=app_name, fill_id = fill.id, app_status=u'未确认', app_key=app_k, app_submit_time=datetime.datetime.now(), enterprise=_enterPrise)
				app_s.save()

			ip.app_status = app_s
			ip.enterprise = _enterPrise
			ip.save()

			ilist = auto_wear_list(request,Ingredients,"enterprise_chemicals",'Ingredients')

			for i in ilist:
				i.app_status = app_s
				i.save()

				cr = ChemicalsRelative(cr_type=it, che_entity=ip.id, igds_entity=i)
				cr.save()

			checkAppStatus(request, 2)
			return HttpResponseRedirect('/chemicals/impList/')
		except Exception,e:
			transaction.rollback()
			result = {'error':e.message if '' else (e.__str__()) }
			return HttpResponse(simplejson.dumps(result))

def impDetail(request,id):
	ip = InterMeditatesPro.objects.get(id = id)
	crs = ChemicalsRelative.objects.filter(cr_type__name='中间产品信息', che_entity=id)
	fill = request.session.get('fill', None)

	iis = []
	for cr in crs:
		ii = Ingredients.objects.get(id=cr.igds_entity.id)
		iis.append(ii)

	return render_to_response('enterprise/chemical_productInfo/imp/impDetail.html', { 'ip':ip, 'status':fill.status, 'iis':iis }, context_instance=RequestContext(request))

@csrf_exempt
def impEdit(request, id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		ip = InterMeditatesPro.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/imp/impEdit.html', { 'ip':ip },context_instance=RequestContext(request))

	if request.method == 'POST':
		ip = InterMeditatesPro.objects.get(id = id)
		auto_wear(request, ip, 'enterprise_chemicals', 'InterMeditatesPro')

		key = request.GET.get('key',None)

		if not key:
			ip.submit_type = 2
		else:
			ip.submit_type = 1

		ip.enterprise = _enterPrise
		ip.save()

		checkAppStatus(request, 2)
		return HttpResponseRedirect('/chemicals/impDetail/%s' % ip.id)

@transaction.commit_on_success
def impDel(request, id):
	try:
		ip = InterMeditatesPro.objects.get(id = id)
		crs = ChemicalsRelative.objects.filter(cr_type__name='产品信息', che_entity=ip.id)

		for cr in crs:
			ii = Ingredients.objects.get(id=cr.igds_entity.id)
			ii.delete()

			cr.delete()

		ip.delete()

		checkAppStatus(request, 2)
		return HttpResponseRedirect('/chemicals/impList/')
	except Exception,e:
		transaction.rollback()
		result = {'error':e.message if '' else (e.__str__()) }
		return HttpResponse(simplejson.dumps(result))

@csrf_exempt
def impElEdit(request, id):
	_enterPrise = request.session.get('ep')
	if request.method == 'GET':
		i = Ingredients.objects.get(id = id)
		return render_to_response('enterprise/chemical_productInfo/imp/impElEdit.html', { 'i':i },context_instance=RequestContext(request))

	if request.method == 'POST':
		i = Ingredients.objects.get(id = id)
		auto_wear(request, i, 'enterprise_chemicals', 'Ingredients')
		i.enterprise = _enterPrise
		i.save()

		cr = i.getBelongstoParent()

		return HttpResponseRedirect('/chemicals/impDetail/%s' % cr.che_entity)